package priv.pattern.strategy;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import priv.pattern.strategy.pojo.StrategyEnum;
import priv.pattern.strategy.service.Strategy;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * 作者：m鹏h
 * 时间；2024/5/29 22:42
 * 描述：
 **/
@Component
public class StrategyContext {
 private final Map<String, Strategy> strategyMap = new ConcurrentHashMap<>();
 @Autowired
 private ApplicationContext applicationContext;

 @PostConstruct
 private void init() {

  /*
   * 项目启动的时候初始化策略实现类
   * @author M鹏H
   * date 2024/5/30
   **/

  strategyMap.putAll(applicationContext.getBeansOfType(Strategy.class));
 }

/*
 * 根据传过来的code,在枚举类中获取策略名称
 * @author M鹏H
 * date 2024/5/30
 **/
 public Strategy getInstance(Integer code) {
  String beanName = StrategyEnum.getByCode(code).getName();
  return this.getInstanceByBeanName(beanName);
 }


 /*
  * 根据策略名称校验出要使用那个策略 并返回
  * @author M鹏H
  * date 2024/5/30
  **/
 private Strategy getInstanceByBeanName(String beanName) {
  if (!StringUtils.isEmpty(beanName)) {
   return strategyMap.get(beanName);
  }
  return null;
 }



}